package com.barbeque.mall.controller.wx;


import com.barbeque.mall.bean.BaseRespVo;
import com.barbeque.mall.bean.BaseRespVoNoData;
import com.barbeque.mall.bean.param.User;
import com.barbeque.mall.bean.user.MarketUser;
import com.barbeque.mall.bean.wx.auth.WxAuthLoginVO;
import com.barbeque.mall.exception.InvalidDataException;
import com.barbeque.mall.util.Constant;
import com.barbeque.mall.util.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.Map;

@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    /**
     * wx/auth/login 账号登录
     *
     * @param map
     * @return com.barbeque.mall.bean.BaseRespVo
     * @author Euphonium
     * @since 2022/07/21
     */
    @PostMapping("login")
    public BaseRespVo login(@RequestBody Map map) throws NoSuchAlgorithmException, InvalidDataException {

        String username = (String) map.get("username");
        String originalPassword = (String) map.get("password");

        // 加密
        String password = MD5Utils.getMd5(originalPassword, Constant.SALT);

        // 认证登录
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(authenticationToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        if (subject.isAuthenticated()) {
            // 登录成功
            MarketUser principal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
            WxAuthLoginVO wxAuthLoginVO = new WxAuthLoginVO();
            WxAuthLoginVO.UserInfoBean userInfo = new WxAuthLoginVO.UserInfoBean();
            userInfo.setNickName(principal.getNickname());
            userInfo.setAvatarUrl(principal.getAvatar());
            wxAuthLoginVO.setUserInfo(userInfo);
            String sessionId = (String) subject.getSession().getId();
            wxAuthLoginVO.setToken(sessionId);
            return BaseRespVo.ok(wxAuthLoginVO);
        }
        // 登录失败
        throw new InvalidDataException("用户名或密码错误");
    }

    /**
     * wx/auth/logout 退出登录
     *
     * @return com.barbeque.mall.bean.BaseRespVoNoData
     * @author Euphonium
     * @since 2022/07/21 13:58
     */
    @PostMapping("logout")
    public BaseRespVoNoData logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVoNoData.ok();
    }

    @GetMapping("noAuthc")
    public BaseRespVoNoData page401() {
        return BaseRespVoNoData.error(501, "未登录");
    }
}